// ==UserScript==
// @name         企业信息查询助手
// @namespace    http://tampermonkey.net/
// @version      0.3
// @icon         https://gezreco.cn/images/logo.ico
// @description  自动抓取企业信息
// @author       gezreco.cn
// @match        https://aiqicha.baidu.com/*
// @match        https://www.qcc.com/*
// @match        https://www.tianyancha.com/*
// @grant        none
// ==/UserScript==
const AIQICHA_PARAMS = ["行政区划", "注册地址"];
const QCC_PARAMS = ["登记机关", "注册地址 "];
const TIANYANCHA_PARAMS = ["登记机关", "注册地址"];

// 搜索指定的公司名称
function searchCompany(companyName) {
    // 获取当前的url
    const hostname = window.location.hostname;
    if (!hostname) {
        return;
    }
    switch (hostname) {
        case 'aiqicha.baidu.com':
            window.location.href = `https://aiqicha.baidu.com/s?q=${companyName}`;
            break;
        case 'www.qcc.com':
            window.location.href = `https://www.qcc.com/web/search?key=${companyName}`;
            break;
        case 'www.tianyancha.com':
            window.location.href = `https://www.tianyancha.com/nsearch?key=${companyName}`;
            break;
        default:
            break;
    }   
}

// 获取并且点击列表中第一个公司名称
function jumpFirstCompany() {
    let a = null;
    // 获取当前的url
    const hostname = window.location.hostname;
    if (!hostname) {
        return;
    }
    switch (hostname) {
        case 'aiqicha.baidu.com':
            a = document.querySelector('.company-list .wrap a');
            break;
        case 'www.qcc.com':
            a = document.querySelector(".msearch table tr .maininfo .copy-title a");
            break;
        case 'www.tianyancha.com':
            a = document.querySelector(".index_list-content__wjkNi .link-click");
            break;
        default:
            break;
    }
    if (a) {
        a.setAttribute("target", "");
        a.click();
    } else {
        alert("没有找到相关的公司，请手动修改公司名称后重新搜索！");
    }
}

// 清空公司列表
function clearCompanyNameList() {
    localStorage.removeItem('companyNameList');
}

// 重置计数器
function resetCounter() {
    localStorage.removeItem('counter');
}

// 重置信息列表
function resetCompanyInfoList() {
    localStorage.removeItem('companyInfoList');
}

// 设置当前公司
function setCurrentCompany(companyName) {
    localStorage.setItem('currentCompany', companyName);
}

// 获取当前公司
function getCurrentCompany() {
    return localStorage.getItem('currentCompany');
}

// 保存解析出的数据到localStorage里面
function saveCompanyInfo(info) {
    let companyInfoList = [];
    // 从localStorage获取CompanyInfoList
    const localInfoList = localStorage.getItem('companyInfoList');
    if (localInfoList) {
        companyInfoList = JSON.parse(localInfoList);
    }
    companyInfoList.push(info);
    // localStorage里面
    localStorage.setItem('companyInfoList', JSON.stringify(companyInfoList));
}

// 解析公司并且保存到localStorage当中
function parseCompanyName(companyNames){
    if (!companyNames) {
        alert("请输入所有公司名称，并且以英文逗号隔开");
        return;
    } else {
        try {
            const companyNameList = companyNames.split(',');
            localStorage.setItem('companyNameList', JSON.stringify(companyNameList));
        } catch (e) {
            alert('请确保以英文逗号进行分隔');
            return;
        }
    }
}

// 解析爱企查详情页字段信息
function parseAiqichaInfo() { 
    let result = [];
    let tds = document.querySelectorAll('#basic-business td');
    tds = Array.from(tds);
    // 遍历所有td找到相关字段的对象
    const tdsList = tds.filter(item => {
        return AIQICHA_PARAMS.includes(item.innerText);
    });
    const companyName = document.querySelector('h1.name').innerText;
    result.push(companyName);
    // 获取内容
    tdsList.forEach( item => {
        const fold = item.nextElementSibling.querySelector('span');
        if(fold) {
            fold.click();
            fold.remove();
        }
        result.push(item.nextElementSibling.innerText);
    })
    return result;
}

// 解析企查查详情页字段信息
function parseQccInfo() { 
    let result = [];
    let tds = document.querySelectorAll(".cominfo-normal .ntable td");
    tds = Array.from(tds);
    // 遍历所有td找到相关字段的对象
    const tdsList = tds.filter(item => {
        return QCC_PARAMS.includes(item.innerText);
    });
    const companyName = document.querySelector('.name-part .title h1').innerText;
    result.push(companyName);
    // 获取内容
    tdsList.forEach(item => {
        const valueSpan = item.nextElementSibling.querySelector('span.copy-value');
        result.push(valueSpan.innerText);
    })
    return result;
}

// 解析天眼查详情页字段信息
function parseTianyanchaInfo() { 
    let result = [];
    let tds = document.querySelectorAll(".dim-section")[1].querySelectorAll("td")
    console.log("tds", tds);
    tds = Array.from(tds);
    // 遍历所有td找到相关字段的对象
    const tdsList = tds.filter(item => {
        return QCC_PARAMS.includes(item.innerText);
    });
    const companyName = document.querySelector('.index_company-name__LqKlo span').innerText;
    result.push(companyName);
    // 获取内容
    tdsList.forEach(item => {
        result.push(item.nextElementSibling.innerText);
    })
    return result;
}


// 解析公司详情页字段信息
function parseCompanyInfo() {
    const hostname = window.location.hostname;
    let result = null;
    if (!hostname) {
        return;
    }
    switch (hostname) {
        case 'aiqicha.baidu.com':
            result = parseAiqichaInfo();
            break;
        case 'www.qcc.com':
            result = parseQccInfo();
            break;
        case 'www.tianyancha.com':
            result = parseTianyanchaInfo();
            break;
        default:
            break;
    }
    result = [getCurrentCompany(), ...result]
    console.log("本次的结果：", result);
    const localCompanyNameList = localStorage.getItem('companyNameList');
    let companyNameList = localCompanyNameList ? JSON.parse(localCompanyNameList) : [];
    console.log("当前爬取进度：",localStorage.getItem('counter'), '/', companyNameList.length);
    // 保存到结果里面
    saveCompanyInfo(result);
}

// 导出数据到csv
function downloadDatas() {
    const localCompanyInfo = localStorage.getItem('companyInfoList');
    const companyInfoList = localCompanyInfo ? JSON.parse(localCompanyInfo) : [];
    console.log("companyInfoList:", companyInfoList);
    let csvContent = "";
    companyInfoList.forEach(function(rowArray) {
        let row = rowArray.join(",");
        csvContent += row + "\r\n";
    });
    // 添加 BOM (Byte Order Mark)
    const BOM = '\uFEFF';
    csvContent = BOM + csvContent;
    // 创建 Blob 对象
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    // 创建一个下载链接
    const link = document.createElement("a");
    if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", "companyInfo.csv");
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// 生成输入框
function createInputArea() {
    return new Promise((resolve, reject) => {
        // document.querySelector('.hot-topic').remove();
        // document.querySelector('.aqc-content-wrapper.no-footer').remove();
        // const indexSearch = document.querySelector('.index-search');
        const documentBody = document.querySelector('body');
        const areabox = document.createElement('div');
        alert("点击确定开始载入脚本")
        areabox.className = "areabox";
        areabox.style.width = "380px";
        areabox.style.border = "2px solid #1c5bff";
        areabox.style.borderRadius = "15px";
        areabox.style.overflow = "hidden";
        areabox.style.backgroundColor = "#fff";
        areabox.style.position = 'absolute';
        areabox.style.bottom = '50px';
        areabox.style.right = '10px';
        const textarea = document.createElement('textarea');
        textarea.style.border = "none";
        textarea.style.width = "100%";
        textarea.style.outline = "none";
        textarea.style.height = "200px";
        textarea.style.fontSize = "14px"
        textarea.style.padding = "10px";
        textarea.value = '重庆工业大数据创新中心有限公司,华为技术有限公司';
        textarea.placeholder = "请在此处粘贴公司名称以英文逗号隔开，例如：公司1,公司2";
        areabox.appendChild(textarea);
        const go = document.createElement("button");
        go.className = "go";
        go.style.position = "absolute";
        go.style.border = "none";
        go.style.outline = "none";
        go.style.bottom = "4px";
        go.style.right = "4px";
        go.style.height = "35px";
        go.style.width = "100px";
        go.style.fontWeight = "700";
        go.style.color = "#fff";
        go.style.fontSize = "14px";
        go.style.borderRadius = "30px";
        go.style.background = "#1c5bff";
        go.style.cursor = "pointer";
        go.innerText = "开始爬取";
        go.addEventListener('click', () => {
            const names = textarea.value;
            if(!names) {
                alert('请在输入框内填写公司名称！');
                return;
            }
            clearCompanyNameList();
            resetCounter();
            resetCompanyInfoList();
            localStorage.setItem('counter', 1);
            parseCompanyName(names);
            setCurrentCompany(names.split(',')[0]);
            searchCompany(names.split(',')[0]);
        });
        const buttonBox = document.createElement("div");
        buttonBox.className = "buttonBox";
        buttonBox.style.width = "800px";
        buttonBox.style.marginTop = "13px";
        areabox.appendChild(go);
        documentBody.appendChild(areabox);
        documentBody.appendChild(buttonBox);
        resolve(1);
    })
}

// 创建继续爬取按钮
function continueBtn() {
    // 获取计数器
    let current = +(localStorage.getItem('counter') || 0);
    // 获取公司名称列表
    const localCompanyNameList = localStorage.getItem('companyNameList');
    let companyNameList = localCompanyNameList ? JSON.parse(localCompanyNameList) : [];
    if (current >= companyNameList.length) {
        return;
    }
    // 创建继续按钮
    const continueBtn = document.createElement("button");
    continueBtn.className = "continue";
    continueBtn.style.border = "none";
    continueBtn.style.outline = "none";
    continueBtn.style.lineHeight = "40px";
    continueBtn.style.padding = "0 14px";
    continueBtn.style.fontWeight = "700";
    continueBtn.style.color = "#fff";
    continueBtn.style.fontSize = "16px";
    continueBtn.style.borderRadius = "30px";
    continueBtn.style.background = "#1c5bff";
    continueBtn.style.cursor = "pointer";
    continueBtn.style.marginRight = "13px";
    continueBtn.innerText = "继续爬取";
    continueBtn.addEventListener('click', () => {
        localStorage.setItem('counter', current + 1);
        window.onload = null;
        const current_company = companyNameList[current];
        setCurrentCompany(current_company)
        searchCompany(companyNameList[current]);
    });
    document.querySelector('.buttonBox').appendChild(continueBtn);
}

// 创建随时下载的逻辑
function downloadBtn() {
    const localCompanyNameList = localStorage.getItem('companyNameList');
    if (!localCompanyNameList) {
        return;
    }
    const continueBtn = document.createElement("button");
    continueBtn.className = "downloadFile";
    continueBtn.style.border = "none";
    continueBtn.style.outline = "none";
    continueBtn.style.lineHeight = "40px";
    continueBtn.style.padding = "0 14px";
    continueBtn.style.fontWeight = "700";
    continueBtn.style.color = "#fff";
    continueBtn.style.fontSize = "16px";
    continueBtn.style.borderRadius = "30px";
    continueBtn.style.background = "#1c5bff";
    continueBtn.style.cursor = "pointer";
    continueBtn.style.marginRight = "13px";
    continueBtn.innerText = "下载数据";
    continueBtn.addEventListener('click', () => {
        downloadDatas();
    });
    document.querySelector('.buttonBox').appendChild(continueBtn);
}

// 判断当前路径
function main() {
    const url = window.location.href;
    const searchPage = /.*\/(s\?q=|nsearch\?key=|search\?key=).*/;
    const infoPage = /\/[^\/]*(company_detail|company|firm)[^\/]*/;
    if (!url) {
        return;
    }
    if (searchPage.test(url)) {
        window.onload = jumpFirstCompany;
    } else if (infoPage.test(url)) {
        window.onload = function () {
            setTimeout(function() {
                // 解析信息
                parseCompanyInfo();
                // 获取当前的计数器
                let current = +(localStorage.getItem('counter') || 0);
                // 从本地获取公司列表
                const localCompanyNameList = localStorage.getItem('companyNameList');
                let companyNameList = localCompanyNameList ? JSON.parse(localCompanyNameList) : [];
                // 判断是否应该结束
                if( current >= companyNameList.length ) {
                    alert('数据搜集结束，点击确认后开启下载');
                    downloadDatas();
                    return;
                } else {
                    localStorage.setItem('counter', current + 1);
                    window.onload = null;
                    const current_company = companyNameList[current];
                    setCurrentCompany(current_company)
                    setTimeout(function() {
                        searchCompany(companyNameList[current]);
                    }, 1500);
                }
            }, 1500);
        }
    } else {
        createInputArea().then(() => {
            downloadBtn();
            continueBtn();
        });
    }
}

main();
